package com.zystudio.func.net;

import android.text.TextUtils;

import com.zystudio.func.other.ZyLog;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * 封装网络请求
 */
public final class ApiRequest {

    private String baseURL;
    /**
     * 网络请求资源路径
     */
    private String path;
    /**
     * 网络请求参数
     */
    private Map<String, Object> params;
    /**
     * 需要设置的Header
     */
    private Map<String, String> headers;

    private ApiRequest() {}

    public static class Builder {
        private String baseURL;
        private final String path;
        private final Map<String, Object> params;
        private final Map<String, String> headers;

        public Builder(String path) {
            this.path = path;
            this.params = new HashMap<>();
            this.headers = new HashMap<>();
        }

        public Builder addBaseURL(String baseUrl){
            this.baseURL = baseUrl;
            return this;
        }

        public Builder addParam(String key, Object value) {
            this.params.put(key, value);
            return this;
        }

        public Builder addHeader(String key, String value) {
            this.headers.put(key, value);
            return this;
        }

        public ApiRequest build() {
            ApiRequest req = new ApiRequest();
            req.path = this.path;
            req.params = this.params;
            req.headers = this.headers;
            req.baseURL = this.baseURL;
            return req;
        }
    }

    /**
     * 提交GET请求
     */
    public void executeGet(final IApiListener callback) {
        String mURL = getURL(this.path);
        if (!params.isEmpty()) {
            mURL += "?" + getRequestParams();
        }
        ZyLog.showLog("request url:"+mURL);
        //开始网络请求
        HttpExecutor executor = HttpExecutor.executor();
        executor.get(mURL, headers, callback);
    }

    public void executePost(final IApiListener callback) {
        //开始网络请求
        HttpExecutor executor = HttpExecutor.executor();
        executor.post(getURL(this.path), getRequestParams(), headers, callback);
    }

    private String getRequestParams() {
        StringBuilder sb = new StringBuilder();
        try {
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                sb.append(entry.getKey()).append("=").append(URLEncoder.encode(String.valueOf(entry.getValue()), "UTF-8")).append("&");
            }
            sb.deleteCharAt(sb.length() - 1);
        } catch (UnsupportedEncodingException e) {
            ZyLog.showLog("generate http param exception:" + e.getMessage());
        }
        return sb.toString();
    }

    private String getBaseUrl() {
        String baseUrl = this.baseURL;
        if (baseUrl.endsWith("/")) {
            baseUrl = baseUrl.substring(0, baseUrl.length() - 1);
        }
        return baseUrl;
    }

    /**
     * 生成完整的网络请求URL
     *
     * @param relativeURL：可以是资源路径或者是完整的URL，如果为空，则请求跟域名
     * @return 返回此次网络请求的URL
     */
    private String getURL(String relativeURL) {
        if (TextUtils.isEmpty(relativeURL)) {
            return getBaseUrl();
        }
        //直接传的全路径
        if (relativeURL.startsWith("http") || relativeURL.startsWith("https")) {
            return relativeURL;
        }
        if (!relativeURL.startsWith("/")) {
            relativeURL = "/" + relativeURL;
        }
        return getBaseUrl() + relativeURL;
    }
}
